'use strict';

/* Directives */
// All the directives rely on jQuery.

angular.module('app.directives', ['ui.load'])

    //页面loading
    .directive('loadingModal', ['$log', function ($log) {
        return {
            restrict: 'AE',
            template: '<div class="loading"><div class="loading-panel"><div class="sk-circle loader" ><div class="sk-circle1 sk-child"></div><div class="sk-circle2 sk-child"></div><div class="sk-circle3 sk-child"></div><div class="sk-circle4 sk-child"></div><div class="sk-circle5 sk-child"></div><div class="sk-circle6 sk-child"></div><div class="sk-circle7 sk-child"></div> <div class="sk-circle8 sk-child"></div><div class="sk-circle9 sk-child"></div><div class="sk-circle10 sk-child"></div><div class="sk-circle11 sk-child"></div><div class="sk-circle12 sk-child"></div></div></div></div>',
        }
    }])

    //收缩隐藏功能
    .directive('toggleBind', ['$log', function ($log) {
        return {
            restrict: 'AE',
            link: function (scope, elem, attrs) {
                elem.on('click', function () {
                    $log.debug('sss', elem);
                    $(attrs.toggleBind).slideToggle(200);
                })

            }
        }
    }])

    //展开功能
    .directive('slideDownBind', function () {
        return {
            restrict: 'AE',
            link: function (scope, elem, attrs) {
                elem.on('click', function () {
                    $(attrs.slideDownBind).slideDown(200);
                })
            }
        }
    })


    //收缩功能
    .directive('slideUpBind', function () {
        return {
            restrict: 'AE',
            link: function (scope, elem, attrs) {
                elem.on('click', function () {
                    $(attrs.slideUpBind).slideUp(200);
                })
            }
        }
    })

    //用于数字输入校验
    .directive('numberOnlyInput', function () {
        return {
            restrict: 'A',
            scope: false,
            require: 'ngModel',
            link: function (scope, elem, attrs, controller) {
                controller.$parsers.push(function (input) {
                    if (input == undefined) return '';
                    // delete non-number string
                    var numberInput = input.replace(/[^0-9]/g, '');
                    if (numberInput != input) {
                        controller.$setViewValue(numberInput);
                        controller.$render();
                    }
                    return numberInput;
                });
            }
        };
    })

    //用于身份证输入校验
    .directive('idCardInput', function () {
        return {
            restrict: 'A',
            scope: false,
            require: 'ngModel',
            link: function (scope, elem, attrs, controller) {
                controller.$parsers.push(function (input) {
                    if (input == undefined) return '';
                    // delete non-number string
                    var numberInput = input;
                    if (numberInput.length == 18 && ( numberInput.substr(17, 1) == 'X' || numberInput.substr(17, 1) == 'x' )) {
                        var tempInput = numberInput.substr(0, 17);
                        numberInput = tempInput.replace(/[^0-9]/g, '') + 'X';
                    } else {
                        numberInput = input.replace(/[^0-9]/g, '');
                    }
                    if (numberInput != input) {
                        controller.$setViewValue(numberInput);
                        controller.$render();
                    }
                    return numberInput;
                });

            }
        };
    })
    //用于金额输入校验
    .directive('amountInput', function () {
        return {
            restrict: 'A',
            scope: false,
            require: 'ngModel',
            link: function (scope, elem, attrs, controller) {
                controller.$parsers.push(function (input) {
                    if (input == undefined) return '';
                    // delete non-number string
                    if (input.length == 1) {
                        var numberInput = input.replace(/[^0-9]/g, '');
                    } else {
                        var numberInput = input.replace(/^(\d+)(\.\d{0,2})?.*$/, "$1$2");
                    }
                    if (numberInput != input) {
                        controller.$setViewValue(numberInput);
                        controller.$render();
                    }
                    return numberInput;
                });
            }
        }
    })
    //菜单栏伸缩组件
    .directive('menuCollapse', function () {
        return {
            restrict: 'AE',
            link: function (scope, ele, attr) {
                $(ele).on("click", "li > a", function (e) {
                    var subMenu = $(this).next(),
                        parent = $(this).closest("li");
                    if (!subMenu.hasClass("sub-menu")) {
                        return
                    }
                    $(".sidebar li").removeClass("open");
                    parent.addClass("open");
                    if ((subMenu.is("ul")) && (subMenu.is(":visible")) && (!$(".app").hasClass("small-sidebar"))) {
                        parent.removeClass("open");
                        subMenu.slideUp(200)
                    }
                    if ((subMenu.is("ul")) && (!subMenu.is(":visible")) && (!$(".app").hasClass("small-sidebar"))) {
                        $(".sidebar ul ul:visible").slideUp();
                        subMenu.slideDown(200);
                        parent.addClass("open")
                    }
                    if (subMenu.is("ul")) {
                        return false
                    }
                    e.stopPropagation();
                    return true
                });
                $(".main-navigation > .nav > li.open").each(function () {
                    $(".sub-menu").hide();
                    $(this).children(".sub-menu").show()
                });
                $(".main-navigation, .slimscroll").each(function () {
                    var data = $(this).data();
                });
            }
        }
    })


    .directive('uiModule', ['MODULE_CONFIG', 'uiLoad', '$compile', function (MODULE_CONFIG, uiLoad, $compile) {
        return {
            restrict: 'A',
            compile: function (el, attrs) {
                var contents = el.contents().clone();
                return function (scope, el, attrs) {
                    el.contents().remove();
                    uiLoad.load(MODULE_CONFIG[attrs.uiModule])
                        .then(function () {
                            $compile(contents)(scope, function (clonedElement, scope) {
                                el.append(clonedElement);
                            });
                        });
                }
            }
        };
    }])
    .directive('uiShift', ['$timeout', function ($timeout) {
        return {
            restrict: 'A',
            link: function (scope, el, attr) {
                // get the $prev or $parent of this el
                var _el = $(el),
                    _window = $(window),
                    prev = _el.prev(),
                    parent,
                    width = _window.width()
                    ;

                !prev.length && (parent = _el.parent());

                function sm() {
                    $timeout(function () {
                        var method = attr.uiShift;
                        var target = attr.target;
                        _el.hasClass('in') || _el[method](target).addClass('in');
                    });
                }

                function md() {
                    parent && parent['prepend'](el);
                    !parent && _el['insertAfter'](prev);
                    _el.removeClass('in');
                }

                (width < 768 && sm()) || md();

                _window.resize(function () {
                    if (width !== _window.width()) {
                        $timeout(function () {
                            (_window.width() < 768 && sm()) || md();
                            width = _window.width();
                        });
                    }
                });
            }
        };
    }])
    .directive('uiToggleClass', ['$timeout', '$document', '$anchorScroll', function ($timeout, $document, $anchorScroll) {
        return {
            restrict: 'AC',
            link: function (scope, el, attr) {
                scope.$on('$stateChangeStart', function (event) {
                    $anchorScroll();
                    // el.removeClass('hide').addClass('active');
                    $(el).click();
                });
                el.on('click', function (e) {
                    e.preventDefault();
                    var classes = attr.uiToggleClass.split(','),
                        targets = (attr.target && attr.target.split(',')) || Array(el),
                        key = 0;
                    angular.forEach(classes, function (_class) {
                        var target = targets[(targets.length && key)];
                        ( _class.indexOf('*') !== -1 ) && magic(_class, target);
                        $(target).toggleClass(_class);
                        key++;
                    });
                    $(el).toggleClass('active');
                    if ($(el).hasClass('active')) {
                        $(el).find('i')[0].className = 'ti-close';
                    } else {
                        $(el).find('i')[0].className = 'ti-menu';
                    }
                    function magic(_class, target) {
                        var patt = new RegExp('\\s' +
                            _class.
                            replace(/\*/g, '[A-Za-z0-9-_]+').
                            split(' ').
                            join('\\s|\\s') +
                            '\\s', 'g');
                        var cn = ' ' + $(target)[0].className + ' ';
                        while (patt.test(cn)) {
                            cn = cn.replace(patt, ' ');
                        }
                        $(target)[0].className = $.trim(cn);
                    }
                });
            }
        };
    }])
    .directive('uiButterbar', ['$rootScope', '$anchorScroll', function ($rootScope, $anchorScroll) {
        return {
            restrict: 'AC',
            template: '<span class="bar"></span>',
            link: function (scope, el, attrs) {
                el.addClass('butterbar hide');
                scope.$on('$stateChangeStart', function (event) {
                    $anchorScroll();
                    el.removeClass('hide').addClass('active');
                });
                scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState) {
                    event.targetScope.$watch('$viewContentLoaded', function () {
                        el.addClass('hide').removeClass('active');
                    })
                });
            }
        };
    }])
    .directive('uiNav', ['$timeout', function ($timeout) {
        return {
            restrict: 'AC',
            link: function (scope, el, attr) {
                var _window = $(window),
                    _mb = 768,
                    wrap = $('.app-aside'),
                    next,
                    backdrop = '.dropdown-backdrop';
                // unfolded
                el.on('click', 'a', function (e) {
                    next && next.trigger('mouseleave.nav');
                    var _this = $(this);
                    _this.parent().siblings(".active").toggleClass('active');
                    _this.next().is('ul') && _this.parent().toggleClass('active') && e.preventDefault();
                    // mobile
                    _this.next().is('ul') || ( ( _window.width() < _mb ) && $('.app-aside').removeClass('show off-screen') );
                });

                // folded & fixed
                el.on('mouseenter', 'a', function (e) {
                    next && next.trigger('mouseleave.nav');
                    $('> .nav', wrap).remove();
                    if (!$('.app-aside-fixed.app-aside-folded').length || ( _window.width() < _mb )) return;
                    var _this = $(e.target)
                        , top
                        , w_h = $(window).height()
                        , offset = 50
                        , min = 150;

                    !_this.is('a') && (_this = _this.closest('a'));
                    if (_this.next().is('ul')) {
                        next = _this.next();
                    } else {
                        return;
                    }

                    _this.parent().addClass('active');
                    top = _this.parent().position().top + offset;
                    next.css('top', top);
                    if (top + next.height() > w_h) {
                        next.css('bottom', 0);
                    }
                    if (top + min > w_h) {
                        next.css('bottom', w_h - top - offset).css('top', 'auto');
                    }
                    next.appendTo(wrap);

                    next.on('mouseleave.nav', function (e) {
                        $(backdrop).remove();
                        next.appendTo(_this.parent());
                        next.off('mouseleave.nav').css('top', 'auto').css('bottom', 'auto');
                        _this.parent().removeClass('active');
                    });

                    $('.smart').length && $('<div class="dropdown-backdrop"/>').insertAfter('.app-aside').on('click', function (next) {
                        next && next.trigger('mouseleave.nav');
                    });

                });

                wrap.on('mouseleave', function (e) {
                    next && next.trigger('mouseleave.nav');
                    $('> .nav', wrap).remove();
                });
            }
        };
    }])
    .directive('uiScroll', ['$location', '$anchorScroll', function ($location, $anchorScroll) {
        return {
            restrict: 'AC',
            link: function (scope, el, attr) {
                el.on('click', function (e) {
                    $location.hash(attr.uiScroll);
                    $anchorScroll();
                });
            }
        };
    }])
    .directive('uiFullscreen', ['uiLoad', function (uiLoad) {
        return {
            restrict: 'AC',
            template: '<i class="fa fa-expand fa-fw text"></i><i class="fa fa-compress fa-fw text-active"></i>',
            link: function (scope, el, attr) {
                el.addClass('hide');
                uiLoad.load('js/libs/screenfull.min.js').then(function () {
                    if (screenfull.enabled) {
                        el.removeClass('hide');
                    }
                    el.on('click', function () {
                        var target;
                        attr.target && ( target = $(attr.target)[0] );
                        el.toggleClass('active');
                        screenfull.toggle(target);
                    });
                });
            }
        };
    }])

    .directive('setNgAnimate', ['$animate', function ($animate) {
        return {
            link: function ($scope, $element, $attrs) {
                $scope.$watch(function () {
                    return $scope.$eval($attrs.setNgAnimate, $scope);
                }, function (valnew, valold) {
                    $animate.enabled(!!valnew, $element);
                });
            }
        };
    }])
    .directive('pagination', [ function () {
        return{
            restrict:"E",
            scope:{
                page:"=",
                pageAction:"&"
            },
            templateUrl:"component/pagination/pagination.html",
            link:function(scope,element,attr){
                scope.preSearch=function(event){
                    if (event.keyCode === 13) {
                        scope.jump(event.target.value);
                    }
                };
                scope.jump = function(index){
                    if( !angular.isNumber(+index) ) return;
                    if( index > parseInt( scope.page.total_pages) ){
                        scope.page.current_page = scope.page.total_pages;
                    }else if( index<1 ){
                        scope.page.current_page = 1;
                    }else{
                        scope.page.current_page = index;
                    }
                    scope.pageAction({pageIndex:scope.page.current_page} );
                };
                //分页往前跳
                scope.prev = function(){
                    scope.page.current_page=parseInt(scope.page.current_page);
                    if( scope.page.current_page<=1) return;
                    scope.page.current_page -=1;
                    scope.pageAction({pageIndex:scope.page.current_page} );
                };
                //分页往后跳
                scope.next = function(){
                    scope.page.current_page=parseInt(scope.page.current_page);
                    if( scope.page.current_page>=scope.page.total_pages) return;
                    scope.page.current_page +=1;
                    scope.pageAction({pageIndex:scope.page.current_page});
                };
                scope.getNumbers = function(num){
                    num=parseInt(num);
                    scope.page.current_page=parseInt(scope.page.current_page);
                    var temp = [];
                    if( num<=8){
                        for( var i=1;i<=num;i++ ){
                            temp.push({val:i});
                        }
                    }else{
                        if(parseInt(scope.page.current_page)<=5){
                            for( var i=1;i<=8;i++ ){
                                temp.push({val:i});
                            }
                            temp.push({val:'……'});
                        }else
                        if( parseInt(scope.page.current_page)>5 &&parseInt(scope.page.current_page)<num-3){
                            temp.push({val:'……'});
                            var test = scope.page.current_page;
                            for( var i=test-3;i<=test+3;i++ ){
                                temp.push({val:i});
                            }
                            temp.push({val:'……'});
                        }else
                        if( parseInt(scope.page.current_page)>=num-3){
                            temp.push({val:'……'});
                            for( var i=num-7;i<=num;i++ ){
                                temp.push({val:i});
                            }
                        }
                    }
                    return temp;
                };

                scope.$watch( 'page.current_page', function(newVal, oldVal){
                //    scope.page.total_pages=10;
                    if( newVal != oldVal ){
                        scope.pageArray = scope.getNumbers(scope.page.total_pages);
                    }
                });
                scope.$watch( 'page.total_pages', function(newVal, oldVal){
              //      scope.page.total_pages=10;
                    if( newVal != oldVal ){
                        scope.pageArray = scope.getNumbers(scope.page.total_pages);
                    }
                });
                scope.pageArray = scope.getNumbers(scope.page.total_pages);
            }
        };
    }])
;